import { CommonParams, I18nConfig } from "../types";
import defaultConfig from "../config";
import path from "node:path";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
import base62 from "base62";

/**
 * 获取配置文件
 * @returns 配置对象
 */
export function getConfig(rootPath?: string) {
  const config: I18nConfig = {
    ...defaultConfig,
  };
  if (!rootPath) {
    return defaultConfig;
  }
  const ignoreFile = path.join(rootPath, ".gitignore");
  if (existsSync(ignoreFile)) {
    const gitignore = readFileSync(ignoreFile, { encoding: "utf-8" });
    // 读取.gitignore文件内容，提取排除项
    const excludeItems = gitignore
      .split("\n")
      .map((item) => item.trim())
      .filter((item) => item && !item.startsWith("#"));
    config.EXCLUDE.push(...excludeItems);
  }
  const configFilePath = path.join(rootPath, "i18n.config.js");
  // 如果配置文件存在，则读取配置文件
  if (existsSync(configFilePath)) {
    const jsConfig = require(configFilePath).default;
    jsConfig.LANG_FILE = path.resolve(rootPath, jsConfig.LANG_FILE);
    jsConfig.TRANS_FILE = path.resolve(rootPath, jsConfig.TRANS_FILE);
    jsConfig.LOG_FILE = path.resolve(rootPath, jsConfig.LOG_FILE);
    return {
      ...config,
      ...jsConfig,
      EXCLUDE: [...config.EXCLUDE, ...(jsConfig.EXCLUDE || [])],
    };
  }
  return config;
}

/**
 * 生成唯一的key
 * @param str
 * @returns
 */
export function genKey(str: string) {
  // 1. 计算SHA-1哈希（160位 → 20字节）
  const hashBuffer = createHash("sha1").update(str).digest();

  // 2. 取前4字节（32位）并转为32位无符号整数
  const truncated = hashBuffer.subarray(0, 4);
  const num = truncated.readUInt32BE();

  // 3. Base62编码压缩为6-8字符
  return base62.encode(num).padStart(6, "0").slice(0, 8);
}

export function updateLocalesFile({
  text,
  CONFIG,
  logger,
}: CommonParams & { text: string }) {
  const { LANG_FILE } = CONFIG;
  if (!existsSync(LANG_FILE)) {
    logger(`本地化文件 ${LANG_FILE} 不存在，创建新文件。`, "warn");
    writeFileSync(LANG_FILE, JSON.stringify({}, null, 2), {
      encoding: "utf-8",
    });
  }
  const localesContent = JSON.parse(
    readFileSync(LANG_FILE, {
      encoding: "utf-8",
    })
  );
  const key = genKey(text);
  if (!localesContent[key]) {
    // 如果没有这个key，则添加
    localesContent[key] = text;
    writeFileSync(LANG_FILE, JSON.stringify(localesContent, null, 2), {
      encoding: "utf-8",
    });
    logger(`已添加新本地化条目：[${key}]${text}`, "info");
  }
  return key;
}
